import axios from "axios";
import { showFailToast, showLoadingToast } from "vant";
import { doLogout, clearToken } from "@/utils/authUtils.js";

const timeout = 10000; // 超时时间

const addLoading = (config) => {
  config.xLoadingTimer = window.setTimeout(() => {
    config.xLoading = showLoadingToast({
      duration: 0,
      message: "加载中...",
      forbidClick: true,
    });

    window.setTimeout(() => {
      closeLoading(config);
    }, config?.timeout || timeout);
  }, 500);
};

const closeLoading = (config) => {
  window.clearTimeout(config?.xLoadingTimer);
  config.xLoading?.close();
};

const service = axios.create({
  baseURL: window.shuchao_config.baseURL,
  timeout,
});

service.interceptors.request.use(
  (config) => {
    let token = sessionStorage.getItem("token");
    if (token) {
      config.headers.Authorization = token;
    }

    addLoading(config);

    return config;
  },
  (error) => {
    closeLoading(error?.config);
    showFailToast("请求异常");
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (res) => {
    closeLoading(res.config);
    if (res.status === 200 && res.data.code === 200) {
      return res.data;
    } else {
      let error = true;

      if (res.status === 401 || res.data?.code === 401) {
        if (res.config.xIsSilent) {
          clearToken();
          error = true;
        } else {
          error = false;
          doLogout(false);
        }
      }

      if (error) {
        showFailToast(res?.data?.msg || "服务异常");
      }

      return Promise.reject(res.data);
    }
  },
  (error) => {
    closeLoading(error?.config);
    showFailToast(error?.data?.msg || "服务异常");
    return Promise.reject(error);
  }
);

export default service;
